package com.gzyz.cheetah.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gzyz.cheetah.entity.dto.DocumentDTO;
import com.gzyz.cheetah.entity.pagerequest.DocumentPageRequest;
import com.gzyz.cheetah.entity.table.Document;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 文档表 Mapper 接口
 * </p>
 *
 * @author xclhove
 * @since 2023-11-06
 */
@Mapper
public interface DocumentMapper extends BaseMapper<Document> {
    /**
     * 统计用户已使用空间
     *
     * @param userId 用户id
     * @return 已使用空间大小
     */
    @Select("select sum(size) from document where user_id = #{userId}")
    public Long countUserDocumentSize(@Param("userId") Integer userId);
    
    /**
     * 搜索文档
     *
     * @param pageRequest 分页请求
     * @return 文档列表
     */
    @Select("select d.id as id, user_id, title, size, d.status as status, comment_status, d.create_time as create_time, d.update_time as update_time, username " +
            "from (select * from document where user_id in (select id from user where username like concat('%', #{searchUser}, '%'))) as d, " +
            "(select id, username from user where username like concat('%', #{searchUser}, '%')) as u " +
            "where d.user_id = u.id " +
            "and is_public = 1 " +
            "and title like concat('%', #{searchTitle}, '%') " +
            "and keywords like concat('%', #{searchKeyword}, '%') " +
            "limit #{pageNo}, #{pageSize} ")
    public List<DocumentDTO> searchDocuments(DocumentPageRequest pageRequest);
    
    /**
     * 统计搜索文档数量
     *
     * @param pageRequest 分页请求
     * @return 文档数量
     */
    @Select("select count(*) " +
            "from document " +
            "where user_id in (select id from user where username like concat('%', #{searchUser}, '%')) " +
            "and is_public = 1 " +
            "and title like concat('%', #{searchTitle}, '%') " +
            "and keywords like concat('%', #{searchKeyword}, '%') ")
    public Integer countSearchDocuments(DocumentPageRequest pageRequest);
}
